﻿using jvm.rtda.heap.clazz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.rtda.heap.pool
{
    class StringPool
    {
        public static Dictionary<string, JObject> caches = new Dictionary<string, JObject>();

        public static JObject StringObject(JClassLoader loader, string str)
        {
            if (caches.ContainsKey(str))
            {
                return caches[str];
            }

            JClass charArrayClass = loader.LoadClass("[C");
            JObject charArray = new JObject(charArrayClass, str.ToCharArray());
            JClass stringClass = loader.LoadClass("java/lang/String");
            JObject strObj = stringClass.NewObject();
            strObj.SetRefVar("value", "[C", charArray);
            caches[str] = strObj;
            return strObj;
        }

        public static string String(JObject obj)
        {
            return new string(obj.GetRefVar("value", "[C").Chars());
        }

        public static JObject StringObject(JObject strObj)
        {
            string str = String(strObj);
            if (caches.ContainsKey(str))
            {
                return caches[str];
            }

            caches[str] = strObj;
            return strObj;
        }
    }
}
